from flask import current_app
from  app.persistence.Order import Order
from datetime import datetime
import uuid
from app.persistence.HouseInfo import HouseInfo
def generate_order_no():
    return datetime.now().strftime('%Y%m%d %H:%M:%S')+str(uuid.uuid4().hex)[:8]

def create_order(tenant_id, house_id, landlord_id, start_date, end_date,
                total_amount, deposit, **kwargs):
    from  app import db
    with current_app.app_context():
        try:
            new_order = Order(
                order_no=generate_order_no(),
                tenant_id=tenant_id,
                house_id=house_id,
                landlord_id=landlord_id,
                start_date=start_date,
                end_date=end_date,
                total_amount=total_amount,
                deposit=deposit,
                **kwargs
            )
            db.session.add(new_order)
            db.session.commit()
            db.session.refresh(new_order)  # 确保所有属性已加载
            db.session.expunge(new_order)
            return new_order
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"Error creating order: {str(e)}")
            return None


def get_order_by_id(order_id):
    with current_app.app_context():
        order = Order.query.filter_by(order_id=order_id).first()
        return order


def get_orders_by_tenant(tenant_id):
    with current_app.app_context():
        orders = Order.query.filter_by(tenant_id=tenant_id).all()
        return orders


def get_orders_by_landlord(landlord_id):
    with current_app.app_context():
        orders = Order.query.filter_by(landlord_id=landlord_id).all()
        return orders



def update_order(order_id, **kwargs):
    from app import db
    with current_app.app_context():
        order = Order.query.filter_by(order_id=order_id).first()
        current_app.logger.debug(f"Updating order {order_id} from status {order.status} to {kwargs.get('status')}")
        if not order:
            return False

        # 获取旧状态用于比较
        old_status = order.status

        # 只允许更新特定字段
        allowed_fields = ['status', 'cancel_reason', 'cancel_by']
        for field, value in kwargs.items():
            if field in allowed_fields and hasattr(order, field):
                setattr(order, field, value)

        try:
            # 如果状态有变化，检查是否需要更新房源状态
            if 'status' in kwargs and old_status != kwargs['status']:
                house = HouseInfo.query.get(order.house_id)
                if house:
                    if kwargs['status'] == 'completed':
                        house.status = 'rented'
                        current_app.logger.info(f"Order {order_id} completed, setting house {order.house_id} to rented")
                    elif kwargs['status'] == 'canceled':
                        house.status = 'published'
                        current_app.logger.info(
                            f"Order {order_id} canceled, setting house {order.house_id} to published")

            db.session.commit()
            db.session.refresh(order)
            return True
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"Error updating order: {str(e)}")
            return False

def delete_order(order_id):
    from app import db
    with current_app.app_context():
        order = Order.query.filter_by(order_id=order_id).first()
        if not order:
            return False

        try:
            db.session.delete(order)
            db.session.commit()
            db.session.expire_all()  # 强制刷新所有会话缓存
            return True
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(f"Error deleting order: {str(e)}")
            return False